import axios from "axios";
import qs from "qs";

/**
 * 【过滤json数据value为空的项】
 * @param data（Object）:        请求数据
 * => return(Object):     返回值：数据均为有效字段(已去除value为空的选项了)
 */
const trimData = (data: any) => {
  data = data || {};
  for (let key in data) {
    if (data[key] === "") {
      delete data[key];
    }
  }
  return data;
};


const httpAxios = (
  method: any,
  url: string,
  params: any,
  headersOpt = {
    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
  },
  mod: string = "yes"
) => {
  let headers: any = {};
  headers["Cache-Control"] = "no-cache"; //接口数据不需要缓存
  headers["X-Requested-With"] = "XMLHttpRequest"; //ajax请求
  headers = Object.assign(headers, headersOpt); //合并头设置
  if (method === "GET" && params) {
    params = trimData(params);
  }

  return new Promise((resolve, reject) => {
    axios({
      method: method,
      headers: headers,
      url: url,
      data: method === "POST" || method === "PUT" ? params : null,
      params: method === "GET" || method === "DELETE" ? params : null,
      withCredentials: true,
    })
      .then((res) => {
        if (res.status == 200) {
          if (res.data.resp_code === 401) {
            funError(res.data.resp_code);
            reject(res);
          } else {
            resolve(res.data);
          }
        } else {
          funError(res.status);
          reject(res);
        }
      })
      .catch(function (err) {
        if (err.request.status === 400 || err.request.status === 401) {
          if (isJSON(err.request.response)) {
            let josn = JSON.parse(err.request.response);
            funError(josn.resp_code);
            reject(err);
          } else {
            funError(err.request.status);
            reject(err);
          }
        } else {
          funError(err.request.status);
          reject(err);
        }
      });
  });
};

const isJSON = (str: string) => {
  if (typeof str == "string") {
    try {
      var obj = JSON.parse(str);
      if (typeof obj == "object" && obj) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    }
  }
};
const funError = (status: number) => {
  if (status === 401) {
    // store.dispatch("goToLogin", "登录已超时,请重新登录");
    //return false;
  } else if (status === 403) {
    //store.dispatch('goToLogin', '暂无权限')
    // message.error("暂无权限，请联系管理员");
    //return false;
  } else if (status == 1) {
    // store.dispatch('goToLogin', '用户名或密码错误')
    // return false;
  } else if (status == 2) {
    //  store.dispatch('goToLogin', '验证码不正确')
    //return false;
  } else {
    //store.dispatch('goToLogin', '网络异常')
    //  return false;
  }
};

const webAxios = (method: any, url: string, params: any, headersOpt = {}) => {
  let header: any = {};
  header["Cache-Control"] = "no-cache"; //接口数据不需要缓存
  header["X-Requested-With"] = "XMLHttpRequest"; //ajax请求
  header["Access-Control-Allow-Methods"] = "*"; //ajax请求
  header["Access-Control-Allow-Origin"] = "*"; //ajax请求
  header["Content-Type"] = "application/json;charset=utf-8"; //ajax请求
  header["Access-Control-Allow-Headers"] =
    "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,key,x-biz,x-info,platinfo,encr,enginever,gzipped,poiid"; //ajax请求
  header = Object.assign(header, headersOpt); //合并头设置
  return new Promise((resolve, reject) => {
    axios({
      method: method,
      headers: header,
      url: url,
      data: method === "POST" || method === "PUT" ? params : null,
      params: method === "GET" || method === "DELETE" ? params : null,
      withCredentials: false,
    })
      .then((res) => {
        if (res.status == 200) {
          resolve(res.data);
        } else {
          reject([]);
        }
      })
      .catch(function (err) {
        reject(err);
      });
  });
};
/**
 * 对外公开方法
 */
export default {
  get: (url: string, params: any = {}, headers: any, mod: string = "yes") => {
    return httpAxios("GET", url, params, headers, mod);
  },
  post: (url: string, params: any, headers: any, mod: string = "yes") => {
    params = qs.stringify(params); //特殊：不能用JSON.stringify()去转，格式和qs.stringify()转的有所差别
    headers = Object.assign(headers, {
      "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
    });
    return httpAxios("POST", url, params, headers, mod);
  },
  postFile: (url: string, params: any, headers: any) => {
    return httpAxios("POST", url, params, headers);
  },
  postFormUrlencoded: (url: string, params: any, headers: any) => {
    params = qs.stringify(params); //特殊：不能用JSON.stringify()去转，格式和qs.stringify()转的有所差别
    return httpAxios("POST", url, params, headers);
  },
  put: (url: string, params: any, headers: any) => {
    return httpAxios("PUT", url, params, headers);
  },
  delete: (url: string, params: any, headers: any) => {
    return httpAxios("DELETE", url, params, headers);
  },
  postJson: (url: string, params: any, headers: any) => {
    return httpAxios("POST", url, params, headers);
  },
  getWeb: (url: string, params: any, headers: any) => {
    return webAxios("GET", url, params, headers);
  },
};
